<?php
namespace modules\comment;
use \phiction\exceptions\no_such_page;
use \phiction\array_utils as arr;
use \modules\ui;
use \modules\auth\api as auth;

class page
{
    static function mapping()
    {
        return [
            // redirections
            '/#post' => '/comment/#post/1',

            // mapping
            '/#post/#page' => 'list',
        ];
    }

    static function list($q, $html, &$args)
    {
        $args['SUBTITLE'] = "评论";
        $post = $args['post'];
        $page = $args['page'];

        $page_link = arr::get_or($args, 'page-link', function ($i) use($post) { return "/comment/$post/$i"; });
        $page_link = function ($i) use ($page_link) { return $page_link($i) . "#comments"; };

        $comments = api::list($q, $args);

        $pager = null;
        $list = ['div', 'class' => 'comment-list'];
        if (count($comments) === 0) {
            $list[] = ['div', 'class' => 'not-exist', "没有评论"];
        } else {
            foreach ($comments as $comment) {
                $id = $comment['id'];
                $author = $comment['author'];
                $body = $comment['body'];
                $list[] = ui::card($author, $body, [
                    [ui::icon_label('删除', 'trash'), 'class' => 'delete-comment', 'data-id' => $id],
                ]);
            }

            $has_next = (count($comments) === 10);
            $pager = ui::pager($page_link, $page, $has_next);
        }

        return $html->mark(['.',
            self::form($q, $html, $args),
            ['a', 'name' => 'comments'],
            $list,
            $pager,
        ]);
    }

    private static function form($q, $html, &$args)
    {
        if (is_null(auth::login_status($q, $args))) {
            $form = ['.',
                "请先",
                ui::format_anchor_controls([ui::login_control()]),
            ];
        } else {
            $post = $args['post'];
            $form = ui::form($html, '/api/comment/add',
                ui::icon_label('评论', 'comment'), [
                    ['body', 'textarea', '想说什么？', 'rows' => 5],
                    ['post', 'hidden', $post],
                ], [], "/post/$post#comments");
        }

        return $html->mark(ui::card("评论", $form));
    }
}

